<?php

declare (strict_types = 1);

namespace app\matter\controller;

use app\matter\BaseController;
use app\admin\validate\DepartmentCheck;
use app\matter\model\AreaModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

//地区管理
class Area extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $list = AreaModel::where('id','<>',0)->select()->toArray();
            return to_assign(0, '', $list);
        } else {
            return view();
        }
    }

    //添加部门
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            if ($param['id'] > 0) {

                $department_array = get_area_son($param['id']);
                if (in_array($param['pid'], $department_array)) {
                    return to_assign(1, '上级地区不能是该地区本身或其下属地区');
                } else {
                    AreaModel::update($param);
                    add_log('edit', $param['id'], $param);
                    return to_assign();
                }
            } else {
                $model = new AreaModel();
                $param['uid'] = $this->uid;
                $model->save($param);
                add_log('add', $model->id, $param);
                return to_assign();
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            $pid = isset($param['pid']) ? $param['pid'] : 0;
            $area_list = set_recursion(get_area_list());
            if ($id > 0) {
                $detail = AreaModel::find($id);
                View::assign('detail', $detail);
            }
            View::assign('area_list', $area_list);
            View::assign('pid', $pid);
            View::assign('id', $id);
            return view();
        }
    }

    //删除
    public function delete()
    {
        $id = get_params("id");
        $count = AreaModel::where(['pid', '=', $id])->count();
        if ($count > 0) {
            return to_assign(1, "该区域下还有子区域，无法删除");
        }
        $users = Db::name('Admin')->where([['area_id', '=', $id], ['status', '>=', 0]])->count();
        if ($users > 0) {
            return to_assign(1, "该区域下还有员工，无法删除");
        }
        if (AreaModel::delete($id) !== false) {
            add_log('delete', $id);
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }

    //获取地区树形节点列表
    public function get_area_tree()
    {
        $list = get_tree(get_area($this->area_id), 0, 3);
        $data['trees'] = $list;
        return json($data);
    }
}
